﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DotNetNuke.Modules.PowerShell.Args
{
	public class ContextArgs : IContextArgs
	{
		private string _eventArgument;

		public string ContextName { get; private set; }

		public IDictionary<string, string> Arguments { get; private set; }

		public string Action { get; private set; }

		public ContextArgs(string eventArgument)
		{
			
			this._eventArgument = eventArgument.Trim();
			this.Arguments = new Dictionary<string, string>();
			this.Action = string.Empty;
			ProcessArg();
		}

		private void ProcessArg()
		{
			var firstSpace = _eventArgument.IndexOf(" ");
			if (firstSpace > -1)
			{
				this.ContextName = _eventArgument.Substring(0, firstSpace);

				var arguments = _eventArgument.Substring(firstSpace + 1);
				foreach (var arg in arguments.Split(' '))
				{
					if(!string.IsNullOrEmpty(arg))
					{
						if (arg.IndexOf(":") > -1)
						{
							var name = arg.Split(':')[0].ToLowerInvariant().Trim();
							var value = arg.Split(':')[1].Trim();

							if (Arguments.ContainsKey(name))
							{
								Arguments[name] = value;
							}
							else
							{
								Arguments.Add(name, value);
							}
						}
						else
						{
							if(string.IsNullOrEmpty(Action) && Arguments.Count == 0)
							{
								Action = arg.Trim().ToLowerInvariant();
							}
						}
					}
				}
			}
			else
			{
				this.ContextName = _eventArgument;
			}

			if(ArgMapping.Maps.ContainsKey(this.ContextName))
			{
				this.ContextName = ArgMapping.Maps[this.ContextName];
			}
		}
	}
}